package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息拦截器
 *
 * @author Zhy
 * @version 1.0
 * @date 2025-03-18 15:00
 */

public class UserInfoInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取请求头中的信息
		String userId = request.getHeader("user-info");
		if (StrUtil.isNotBlank(userId)) {
			UserContext.setUser(Long.valueOf(userId));
		}

		return true;
	}

	@Override
	public void afterCompletion(
		HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex
	) throws Exception {
		UserContext.removeUser();
	}
}
